﻿using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace Simp.Model.CoreExpressions.Sequences
{
	/// <summary>Encapsulates an expression forcing the evaluation of a sequence into an explicit form.</summary>
	[ExpressionName("List")]
	[ParameterPolicy("sequence")]
	[DebuggerDisplay("{ExpressionHelper.Serialize(this)}")]
	public class ListExpression : IExpression, ISimplifiableExpression
	{
		#region ISimplifiableExpression Members
		IExpression ISimplifiableExpression.Simplify(SimplificationMode simplificationMode, params IExpression[] parameterList)
		{
			if (parameterList == null)
			{
				throw new ArgumentNullException("parameterList");
			}
			if (parameterList.Length == 1)
			{
				ExplicitSequenceExpression sequence;
				CompositeExpression composite = ExpressionHelper.TryGetComposite(parameterList[0], out sequence);

				if (sequence != null)
				{	//	Function call is no longer necessary, the underlying sequence already is an explicit sequence
					return composite;
				}
				else
				{
					ISequenceAccessor accessor = ExpressionHelper.GetAccessor(composite);

					if (accessor == null)
					{
						return null;
					}
					else
					{
						List<IExpression> expressionList =
							new List<IExpression>(new SyncSimplifyingSequenceAccessor(accessor));

						return new CompositeExpression(
							new ExplicitSequenceExpression(expressionList.Count),
							expressionList.ToArray());
					}
				}
			}

			return null;
		}
		#endregion
	}
}